<template>
  <div>
    <!-- 特殊车辆配件类型保修期维护 -->
    <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="90" @filterChange="changeHandle"></TopFilter>
    <Spin :spinning="loading" tip="导入中，请稍后...">
      <!-- table -->
      <FilterTable
        ref="table"
        :columns="columns"
        :params="fetchParams"
        :fetchapi="fetchapi"
        :datakey="'records'"
        :onColumnsChange="(columns) => (this.columns = columns)"
        :onRowSelectChange="selectChange"
        :is-select-column="false"
      >
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">新增</multiuse-button>
          <multiuse-button type="primary" :click="exportFileBtn.bind()">导出</multiuse-button>
          <multiuse-button size="small" type="primary" :loading="exportLoading" :click="downloadTemplate.bind()">下载模板</multiuse-button>
          <multiuse-button size="small" icon="el-icon-upload" @click="showImportFun()" >导入</multiuse-button>
        </template>
      </FilterTable>
    </Spin>
    <BaseDialog :visible.sync="visible" :title="dialogTitle" width="850px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <Vehicle @close="close" @save="save"></Vehicle>
    </BaseDialog>
    <BaseDialog :visible.sync="visibleAdd" :title="'特殊车辆配件类型保修期新增'" width="850px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <AddForm @close="closeAdd" @save="saveAdd"></AddForm>
    </BaseDialog>
    <BaseDialog :visible.sync="visibleEdit" :title="'特殊车辆配件类型保修期编辑'" width="850px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <EditForm :rowData="rowData" @close="editclose" @save="editsave"></EditForm>
    </BaseDialog>
    <BaseDialog :visible.sync="showImport" icon="el-icon-upload" :closable="false" title="导入" width="800px" destroyOnClose :containerStyle="{ height: '100%', overflow: 'auto'  }">
      <importExcel @close="showImport = false" @importclose="colseImportFun()" url="/api/cms_claimfac/rPSpecialPtOil/importExcel"/>
    </BaseDialog>
  </div>
</template>
<script>
import { getToken, getAppId, getUserId } from '@/assets/js/auth';
import { getListByPage, newSave, excelExport, editSave, deleteOne, downloadModel, getListForExport,exporturl } from '@/api/claim/factory/SpecialCarPartTypeWarrantyMaintainOil';
import { getPart} from '@/api/dictionary/index';
import AddForm from './AddForm.vue';
import Vehicle from '@/pages/claimDemage/tools/ModelVehicle.vue';
import { exportExcelFile } from '@/utils/index';
import EditForm from './EditForm.vue';
import importExcel from '@/pages/claimDemage/tools/importExcel.vue';

export default {
  components: {
    Vehicle,
    AddForm,
    EditForm,
    importExcel
  },
  data() {
    return {
      headersObj: {
        jwt: getToken(),
        appId: getAppId(),
        userId: getUserId(),
        userAgent: 'pc'
      },
      visible: false,
      showImport: false,
      collapse: true,
      visibleEdit: false,
      exportLoading: false,
      rowData: {},
      fetchapi: getListByPage,
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      dialogTitle: '选择车型',
      visibleAdd: false,
      loading: false,
      fileList: []
    };
  },
  created() {
    this.chuqi();
  },
  methods: {
    async chuqi() {
      const res = await getPart();
      if (res.resultCode == 200) {
        this.topFilterInit.find(x => x.fieldName == 'typeId').initialValue = '';
        this.topFilterInit.find(x => x.fieldName == 'typeId').itemList = res.data.map(y => ({ text: y.name, value: y.code }));
      }
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = Object.assign({}, this.fetchParams, val);
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    close() {
      this.visible = false;
    },
    chooseOrderNo() {
      this.visible = true;
    },
    save(obj) {
      this.topFilterInit.find((x) => x.fieldName == 'modelId').initialValue = obj[0].modelCode;
      this.visible = false;
    },
    add() {
      this.visibleAdd = true;
    },
    closeAdd() {
      this.visibleAdd = false;
    },
    emitFun(val) {
      this.rowData = val;
      this.visibleEdit = true;
    },
    editclose() {
      this.visibleEdit = false;
    },
    editsave() {
      this.visibleEdit = false;
      this.fetchParams = { ...this.fetchParams };
    },
    saveAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    // 删除
    async delFun(data) {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let res;
          res = await deleteOne({ ptId: data.ptId });
          if (res.resultCode != 200) {
            this.$notify.error({title: '提示信息', message: res.errMsg || '删除失败!'});
          } else {
            this.$notify.success({title: '提示信息', message: '删除成功!'});
            // 重新加载
            this.fetchParams = {...this.fetchParams};
          }
        });
    },
    //下载模板
    downloadTemplate() {
      this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.exportLoading = true;
        downloadModel().then((res) => {
          console.log(res);
          exportExcelFile(res.data, '特殊车辆配件类型保修期维护导入模板');
          this.exportLoading = false;
        });
      });
    },
    // 导出
  async  exportFileBtn() {
      let json = Object.assign({}, { CODE: 'CODE_00000105' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
    },
    showImportFun() {
      this.showImport = true;
    },
    colseImportFun() {
      this.showImport = false;
      this.fetchParams = { ...this.fetchParams };
    },
    showErrorList(response) {
      if(response.resultCode == 200){
        this.$notify.success({ title: '提示信息', message: '导入完成!' });
        this.fetchParams = { ...this.fetchParams };
        this.fileList = [];
        this.loading = false;
      } else {
        this.fileList = [];
        this.$notify.error({ title: '提示信息', message: response.errMsg });
        this.loading = false;
      }
    },
    handleExceed(error) {
      this.loading = false;
    },
    beforeUpload() {
      this.loading = true;
    },
    //搜索数据
    topFilterInitFun() {
      return [
        { type: 'INPUT', label: 'VIN', fieldName: 'vin', placeholder: '请输入VIN...', initialValue: '' },
        { type: 'INPUT', label: '配件代码', fieldName: 'partCode', placeholder: '请输入配件代码...', initialValue: '' },
        { type: 'INPUT', label: '配件名称', fieldName: 'partName', placeholder: '请输入配件名称...', initialValue: '' },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modelId',
          placeholder: '请输入车型...',
          initialValue: '',
          unitRender: (p) => {
            return (
              <div>
                <multiuse-button icon="el-icon-search" onClick={() => this.chooseOrderNo()} />
              </div>
            );
          }
        },
        // { type: 'SELECT', label: '配件类型', fieldName: 'typeId', placeholder: '请选择配件类型...', initialValue: '', itemList: [], filterable: true },
        {
          type: 'INPUT',
          label: '保修期',
          fieldName: 'rpPeriod',
          unitRender: () => {
            return <span>(月)</span>;
          },
          rules: [
            {
              validator: (rule, value, callback) => {
                if(value) {
                  if (Number.isInteger(Number(value))) {
                    callback();
                  } else {
                    callback(new Error('请输入数字值'));
                  }
                } else {
                  callback();
                }
              },
              trigger: ['blur', 'change'],
            },
          ],
          placeholder: '请输入保修期...',
          initialValue: '',
        },
        {
          type: 'INPUT',
          label: '保修里程',
          fieldName: 'rpMile',
          unitRender: () => {
            return <span>(KM)</span>;
          },
          rules: [
            {
              validator: (rule, value, callback) => {
                if(value) {
                  if (Number.isInteger(Number(value))) {
                    callback();
                  } else {
                    callback(new Error('请输入数字值'));
                  }
                } else {
                  callback();
                }
              },
              trigger: ['blur', 'change'],
            },
          ],
          placeholder: '请输入保修里程...',
          initialValue: '',
        },
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          fixed: 'left',
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          render: (props, h) => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.emitFun(props.row)}>
                  编辑
                </multiuse-button>
                <multiuse-button size="mini" type="text" onClick={() => this.delFun(props.row)}>
                  删除
                </multiuse-button>
              </div>
            );
          },
        },
        { title: '配件代码', dataIndex: 'partCode', sorter: true },
        { title: '配件名称', dataIndex: 'partName', sorter: true },
        { title: '车型代码', dataIndex: 'modelId', sorter: true },
        { title: '车型名称', dataIndex: 'modelName', sorter: true },
        { title: 'VIN', dataIndex: 'vin', sorter: true, width: 150 },
        { title: '保修期（月）', dataIndex: 'rpPeriod', sorter: true },
        { title: '保修里程（KM）', dataIndex: 'rpMile', sorter: true },
        { title: '备注', dataIndex: 'remarks', sorter: true },
        { title: '创建人', dataIndex: 'createdBy', sorter: true, width: 150},
        { title: '创建时间', dataIndex: 'createdAt', sorter: true },
        { title: '修改人', dataIndex: 'updatedBy', sorter: true, width: 150},
        { title: '修改时间', dataIndex: 'updatedAt', sorter: true },
      ];
    },
  }
};
</script>

<style lang="less" scoped></style>
